package net.mysoft.budgetsoft.system.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import net.mysoft.budgetsoft.system.dao.OrgDao;
import net.mysoft.budgetsoft.system.dao.UserDao;
import net.mysoft.budgetsoft.system.domain.PageData;
import net.mysoft.budgetsoft.system.domain.TOrg;
import net.mysoft.budgetsoft.system.domain.TRole;
import net.mysoft.budgetsoft.system.domain.TUser;
import net.mysoft.budgetsoft.system.service.UserService;
import net.mysoft.framework.base.BaseAction;
import net.mysoft.framework.util.Maps;
import net.mysoft.framework.util.Tool;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.stereotype.Service;

@SuppressWarnings({"rawtypes", "unchecked"})
@Service
public class UserServiceImpl implements UserService {
	
	@Autowired
	private UserDao userDao;
	@Autowired
	private OrgDao orgDao;

	@Override
	public PageData<TUser> getUserDataGrid(Map map) {
		int pageNo = Tool.toInt(map.get("page"));
		int pageSize = Tool.toInt(map.get("rows"));
		PageData<TUser> page = new PageData<TUser>(pageNo, pageSize);
		/*page.setRows(userDao.queryPageByHql("select new map(id as id, name as name, age as age, "
				+ "sex as sex, tel as tel, email as email, birthday as birthday, job as job, "
				+ "userNo as userNo, org.name as orgName) from TUser", pageNo, pageSize));*/
		page.setRows(userDao.queryPageByHql("select new map(user.id as id, user.name as name, user.age as age, "
				+ "user.sex as sex, user.tel as tel, user.email as email, user.birthday as birthday, user.job as job, "
				+ "user.userNo as userNo, org.name as orgName, user.loginName as loginName) from TUser as user left join user.org as org", pageNo, pageSize));
		return page;
	}

	@Override
	public void saveUser(TUser user) {
		String orgId = user.getOrg().getId();
		if(StringUtils.isBlank(orgId)) user.setOrg(null);
		else user.setOrg(orgDao.load(TOrg.class, orgId));
		user.setPwd(new Md5PasswordEncoder().encodePassword(BaseAction.DEFAULT_PWD, null));
		System.err.println(user.getPwd().length());
		user.setPwdView(BaseAction.DEFAULT_PWD);
		userDao.save(user);
	}

	@Override
	public List getOrgTree() {
		List<TOrg> orgs = orgDao.find("from TOrg");
		List tree = new ArrayList();
		for(TOrg org:orgs) {
			Map map = new Maps().put("id", org.getId()).put("text", org.getName()).build();
			if(org.getParent()!=null) map.put("pid", org.getParent().getId());
			tree.add(map);
		}
		return tree;
	}

	@Override
	public void delUsers(String para) {
		if(StringUtils.isNotBlank(para)) {
			String[] ids = para.split(",");
			for(String id:ids) {
				TUser user = userDao.load(TUser.class, id);
				userDao.delete(user);
			}
		}
	}
	
}
